<template>
    <view class="main">
		  <view  v-for="(pics, index) in imgList" :key="index">
			  <view v-if="totalNo===index">
				<view id='picbox' :class="{'white-bg': isShow}"  :style="{'background-image':!isShow?'url('+pics.image+')':'none'}">
					<view class="pic" :class="{'show-pic': isShow}" v-for="(item,index) in pic" :id="index" :key="index" :data-index='dataIndexs[index]'
						@touchstart.stop.prevent="touchStart($event,index,pics)" @touchmove.stop.prevent="touchmove($event,index)"
						@touchend.stop.prevent="touchEnd($event,index)" :style="{'background-image': 'url('+pics.image+')','background-position': item.backgroundPosition,'left': item.left + 'px','top': item.top + 'px','z-index': item.zIndex,'transition': item.transition}"></view>
				</view>
			  </view>
		</view>
       <view class='controller' >
		     <view class='controllerColind' >
			  <view class="progress">
			  		<text>{{ totalNo+1}}/{{imgList.length}}</text>
			  </view>
			   <u-button  @click="nextQuestion('up')" v-if="totalNo>0"  class="buttonBorder">
					<img  src="https://www.afbeijing.net/static_resources/assets/up.png" style="width:20rpx; height: 20rpx;">
			   </u-button>
			   </button>
				<view id='go' @click="go"> 
					<img v-if="!isShow" src="https://www.afbeijing.net/static_resources/assets/sta.png" style="width:45rpx; height: 45rpx;" >
					<img v-if="isShow" src="https://www.afbeijing.net/static_resources/assets/updata.png" style="width:45rpx; height: 45rpx;" >
				</view>
				<u-button  @click="nextQuestion('down')"  :disabled="!canGoNext" class="buttonBorder">
					 <img src="https://www.afbeijing.net/static_resources/assets/down.png" style="width:20rpx; height: 20rpx;" >
				</u-button>
				<u-button class="custom-style" :customStyle="{'height':' 50px;','width':' 50px;'}" @click="completeGames" shape="circle" type="warning" text="提交"></u-button>
			</view>
			<!-- <view class='image-title'>原图：</view> -->
            <img class="original-image" :src="imgList[totalNo].image">
        </view>
    </view>
</template>

<script>
	import { isIPhone7Plus,isHarmonyOS,isProMaxDevice } from './dev.js';
	import { fourSelectGame,completeGame } from "../../../api/index"
    export default {
        data() {
            return {
				vws:null,
				vhs:null,
				totalNo:0,
				 isIPhone7PlusLandscape: false,
				 canGoNext:false,
                pic: [{
                        left: 0,
                        top: 0,
                        // backgroundPosition: '-10rpx -10px',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 100,
                        top: 0,
                        // backgroundPosition: '-100rpx 0px',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 200,
                        top: 0,
                        // backgroundPosition: '-200rpx 0px',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 0,
                        top: 100,
                        // backgroundPosition: '0px -100rpx',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 100,
                        top: 100,
                        // backgroundPosition: '-100rpx -100rpx',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 200,
                        top: 100,
                        // backgroundPosition: '-200rpx -100rpx',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 0,
                        top: 200,
                        // backgroundPosition: '0px -200rpx',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 100,
                        top: 200,
                        // backgroundPosition: '-100rpx -200rpx',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                    {
                        left: 200,
                        top: 200,
                        // backgroundPosition: '-200rpx -200rpx',
                        zIndex: 0,
                        transition: 'all 0.5s ease 0s'
                    },
                ],//循环9块拼图
				errorNo:0,//错误值
                picbox: '',
                isShow: false,
				imgList:[{}],//图片img 必须有个空字符不然会报错，暂时这样后面优化
                dataIndexs: [1, 2, 3, 4, 5, 6, 7, 8, 9],// 循环9块
                dx: '',
                dy: '',
				gameId:0,//当前提交id
                newLeft: '',
                newtop: '',
                picWidth: '',
				clsCrsId:null,
				crsId:null,
                picHeight: '',
                picboxWidth: '',
                picboxHeight: '',
                startX: '',
                startY: '',
                endX: '',
                endY: '',
                imageUrl: 'https://www.afbeijing.net/static_resources/assets/wdxx.png'
            }
        },
        onReady() {
          this.getPic()
        },
		onShow() {
			// uni.$on('update', function(data) {
			//        uni.redirectTo({
			// 	   url: '/src/views/pageStudy/pagePlay/zhishidianhuigu/pintu/index' // 确保 URL 唯一以避免缓存问题
			// 	 });     //触发更新后
			//  })
		},
		onLoad(e) {
			console.log(e,'2222222')
			this.crsId=e.crsId
			this.clsId=e.clsId
			this.clsCrsId =Number(e.id)
			var query = wx.createSelectorQuery();
			var picbox = query.select('#picbox');
			var pic = query.selectAll('.pic');
			pic.boundingClientRect(data => {
			    this.picHeight = data[0].height;
			    this.picWidth = data[0].width;
			}).exec();
			picbox.boundingClientRect(data => {
				console.log(data,'---')
			    this.picbox = data;
			    this.picboxHeight = data.height;
			    this.picboxWidth = data.width;
			}).exec();
			this.selectGameList()
			console.log( this.picbox)
		},
		 watch: {
			  pic: {
			       handler(newVal, oldVal) {
					   this.pic=newVal
			         console.log('myValue changed:', newVal, oldVal);
			       },
			       immediate: true
			    }
		   //  // 监听message的变化
		   //  pic(newVal, oldVal) {
		   //    console.log(newVal,'newVal');
			  // this.pic=newVal
		   //    // 你可以在这里根据新的值进行相应的操作
		   //  }
		  },
		  mounted() {
		 
		  },
        methods: {
			//
			getPic(){
				const vw = wx.getSystemInfoSync().windowWidth;
				const vh = wx.getSystemInfoSync().windowHeight;
				var itemWidth = (vw - 100) / 3 -32;;
				var itemHeight = (vh - 60) / 3 - 2;
				var isIPhone7Pluss=isIPhone7Plus()
				console.log(isIPhone7Pluss)
				if (isIPhone7Pluss) {
					// 如果是 iPhone 7 Plus，可以在这里执行特定操作
					console.log('当前设备是 iPhone 7 Plus');
					// 检测当前是横屏还是竖屏
					itemWidth = (vw - 100) / 3 -25;
					itemHeight = (vh - 60) / 3 - 2;
				} else {
					 itemWidth = (vw - 100) / 3 -30;
					console.log('当前设备不是 iPhone 7 Plus');
				}
				var isHarmonyOSs=isHarmonyOS()
				if(isHarmonyOSs){
					console.log('当前设备是华为');
				itemWidth = (vw - 100) / 3 -35;
				itemHeight = (vh - 60) / 3 - 2;
				}
				if(isProMaxDevice()){
					console.log('当前设备是 iPhonemax');
					itemWidth = (vw - 100) / 3 -40;
				}
				for (let i = 0; i < this.pic.length; i++) {
					const row = Math.floor(i / 3);
					const col = i % 3;
					this.pic[i].left = col * itemWidth;
					console.log(col,'---------')
					this.pic[i].top = row * itemHeight;
					
					if(col===2||col===5||col===8){
						this.pic[i].backgroundPosition = `-${col * itemWidth+5}px -${row * itemHeight}px`;
					}else if(col===1||col===4||col===7){
						// const itemWidth = (vw - 100) / 3 -40;
						this.pic[i].backgroundPosition = `-${col * itemWidth}px -${row * itemHeight}px`;
					}else{
						this.pic[i].backgroundPosition = `-${col * itemWidth}px -${row * itemHeight}px`;
					}
				}
			},
		 
			//完成拼图
			completeGames(){
				if(this.isShow&&this.clsCrsId){
					if (this.dataIndexs.join('') == '123456789'&&this.gameId!==0) {
						this.sumbPic()

					}else{
						//错误提示
						this.errorNo++
						// this.sumbPic() 实验用的
						  uni.$u.toast('错误拼图，请重试') 
						console.log(this.errorNo)
					}
				}else{
				   uni.$u.toast('请开始游戏在提交') 
				}
				
			},
			// 提交成功
			sumbPic(){
				var jsonData = {
					clsId:this.clsId,
					clsCrsId:this.clsCrsId,
					crsId:this.crsId,
					tryNum:this.errorNo,
					gameId:Number(this.gameId)-1
				};
				//完成拼图提示
				let _this = this;
				completeGame(jsonData).then(response => {
					console.log(response)
					if (response.code === 0) {
						var _this=this
						uni.showModal({
						    title: '提示',
						    showCancel: false,
						    content: '恭喜你完成了拼图！',
						    success: function(res) {
						        if (res.confirm) {
									this.canGoNext=true
						            _this.isShow = false;
									_this.selectGameList()
									_this.nextQuestion('down')//自动下一个
									
						        }
						    }
						});
						// this.imgList=response.data
					}else{
						//	
					}
				})
			},
			//下一个拼图
			nextQuestion(e){
				console.log(e)
				if((this.totalNo+1)===this.imgList.length&&e!=='up'){
					// wx.showModal({
					//   title: '没有题了',
					//   showCancel: false,
					// });
					uni.redirectTo({
						url: '/src/views/pageStudy/common/huodejifen/index?jifen='+'5'+'&showButton=false' // 恭喜完成页面 积分后面的5为动态传递
					});
				}
				else{
					if(e==='up'){
						this.totalNo--
						this.selectGameList()
					}else{
						this.totalNo++
					}
				}
			},
			//查询拼图游戏
			selectGameList(){
				// this.clsCrsId=494
				// this.crsId='ag300-cls301-crs001'
				var jsonData = {
					clsCrsId:this.clsCrsId,
					crsId:this.crsId,
					pageNum:1,
				};
				fourSelectGame(jsonData).then(response => {
					console.log(response)
				if (response.code === 0) {
					this.imgList=response.data
				}else{
					this.nodeIf=false
					uni.$u.toast(response.msg) 
				}
				}).catch(errors => {
									// uni.$u.toast(errors)
				})
			},
			//开始游戏
            go() {
				console.log(this.pic)
				 this.getPic()
                this.isShow = true;
                for (var i = 0; i < 20; i++) { //随机打乱
                    var a = Math.floor(Math.random() * 9);
                    var b = Math.floor(Math.random() * 9);
                    if (a!= b) {
                        this.random(a, b);
                    }
                }
            },
            random(a, b) {
				console.log(a, b,'-------')
                var aEle = this.pic[a];
                var bEle = this.pic[b];
                var _left;
                _left = aEle.left;
                aEle.left = bEle.left;
                bEle.left = _left;
                var _top;
                _top = aEle.top;
                aEle.top = bEle.top;
                bEle.top = _top;
                var _index;
                _index = this.dataIndexs[a];
                this.dataIndexs[a] = this.dataIndexs[b];
                this.dataIndexs[b] = _index;
            },
            touchStart(e, index,item) {
				console.log(e)
				this.gameId=e.target.id-1
                if (!this.isShow) {
                    return false;
                }
                this.pic[index].zIndex = 100; //设置拖拽元素的z-index值，使其在最上面。
                this.dx = e.touches[0].pageX - this.pic[index].left; //记录触发拖拽的水平状态发生改变时的位置
                this.dy = e.touches[0].pageY - this.pic[index].top; //记录触发拖拽的垂直状态发生改变时的位置
                this.startX = this.pic[index].left; //记录当前初始状态水平发生改变时的位置
                this.startY = this.pic[index].top; //offsetTop等取得的值与this.style.left获取的值区别在于前者不带px,后者带px
                this.pic[index].transition = 'none';
            },
            touchmove(e, index) {
                if (!this.isShow) {
                    return false;
                }
                this.newLeft = e.touches[0].pageX - this.dx; //记录拖拽的水平状态发生改变时的位置
                this.newtop = e.touches[0].pageY - this.dy;
                if (this.newLeft <= -this.picWidth / 2) { //限制边界代码块，拖拽区域不能超出边界的一半
                    this.newLeft = -this.picWidth / 2;
                } else if (this.newLeft >= (this.picboxWidth - this.picWidth / 2)) {
                    this.newLeft = (this.picboxWidth - this.picWidth / 2);
                }
                if (this.newtop <= -this.picHeight / 2) {
                    this.newtop = -this.picWidth / 2;
                } else if (this.newtop >= (this.picboxHeight - this.picHeight / 2)) {
                    this.newtop = (this.picboxHeight - this.picHeight / 2);
                }
                this.pic[index].left = this.newLeft;
                this.pic[index].top = this.newtop; //设置目标元素的left,top
            },
            change(obj, x, y) { //交换函数，判断拖动元素的位置是不是进入到目标原始1/2，这里采用绝对值得方式
                for (var i = 0; i < this.pic.length; i++) { //还必须判断是不是当前原素本身。将自己排除在外
                    if (Math.abs(this.pic[i].left - x) <= this.picWidth / 2 && Math.abs(this.pic[i].top - y) <= this.picHeight / 2 &&
                        i!=
                        obj)
                        return i;
                }
                return obj; //返回当前
            },
            touchEnd(e, index) {
                if (!this.isShow) {
                    return false;
                }
                this.pic[index].zIndex = 0;
                this.pic[index].transition = 'all 0.5s ease 0s'; //添加css3动画效果
                this.endX = e.changedTouches[0].pageX - this.dx;
                this.endY = e.changedTouches[0].pageY - this.dy; //记录滑动结束时的位置，与进入元素对比，判断与谁交换
                var obj = this.change(e.target.id, this.endX, this.endY); //调用交换函数
                if (obj == e.target.id) { //如果交换函数返回的是自己
                    this.pic[obj].left = this.startX;
                    this.pic[obj].top = this.startY;
                } else { //否则
                    var _left = this.pic[obj].left;
                    this.pic[obj].left = this.startX;
                    this.pic[index].left = _left;
                    var _top = this.pic[obj].top;
                    this.pic[obj].top = this.startY;
                    this.pic[index].top = _top;
                    var _index = this.dataIndexs[obj];
                    this.dataIndexs[obj] = this.dataIndexs[index];
                    this.dataIndexs[index] = _index; //交换函数部分，可提取
                }
                
            }
        }
    }
</script>
<style lang="scss" scoped>
	@function tovmin($rpx) {
		//$rpx为需要转换的字号
		@return #{$rpx * 100 / 750}vmin;
	}
</style>
<style lang="scss" scoped>
	.custom-style{
		border-radius: 100rpx;
	}
	.progress{
		text-align: center;
	}
	.controllerColind{
		background: #fff;
		border-radius: 15rpx;
		padding-top: 5px;
		padding-bottom: 5rpx;
		/* padding: 5rpx; */
	}
	::v-deep .u-button--info{
		border: none !important;
		background: none !important;
		height: 35rpx !important;
		/* margin-top: 10rpx; */
		margin-bottom: 10rpx;
	}
	.buttonBorder{
		/* height: 20rpx; */
		background: none !important;
		border: none !important;
		box-sizing: border-box;
	}
	.main{
		display: flex;
		/* justify-content: space-between; */
	}
   .controller {
        /* display: flex; */
		margin-top: 20rpx;
        /* width: calc(100vw - 60px); */
        /* justify-content: space-between; */
        /* align-items: center; */
    }

    #picbox {
        position: relative;
        width: calc(100vw - 170rpx);
		background-repeat: no-repeat;
        height: calc(100vh - 60rpx);  /* 根据横版调整为使用vh来控制高度，可根据实际情况微调 */
        background-size:calc(100vw - 170rpx) calc(100vh - 60rpx);
        margin: 30rpx 30rpx 30rpx 30rpx;
    }

   .image-title {
        margin: 0rpx auto;
        /* width: calc(100vw - 60px); */
        font-size: 14rpx;
    }

    #picbox.white-bg {
        /* background: #FFFFFF; */
    }

    #go {
        width:100%;
        line-height: 40rpx;
        /* border: 1px solid #333333; */
        font-size: 22rpx;
        text-align: center;
    }

   .original-image {
	    border-radius: 10rpx;
        width: 80rpx;
		margin-top: 10rpx;
        height: 40rpx;  /* 根据横版调整高度计算方式 */
    }

   .pic {
        opacity: 0;
	    background-repeat: no-repeat;
        width: calc((100vw - 170rpx)/3 - 5rpx);
        height: calc((100vh - 60rpx)/3 - 0rpx);  /* 根据横版调整高度计算方式 */
        float: left;
		background-size:calc(100vw - 170rpx) calc(100vh - 38rpx);
        position: absolute;
        transition: all 0.5s ease 0s;
    }

   .pic.show-pic {
        opacity: 1;
        display: block;
    }
	 /* 针对7P设备的特殊样式优化 */
	@media only screen 
	  and (min-device-width: 736px) 
	  and (max-device-width: 736px) 
	  and (min-width: 736px) 
	  and (max-width: 736px) 
	  and (orientation: landscape) {
	   #picbox {
	    position: relative;
	    width: calc(100vw - 150rpx) !important;
	    background-repeat: no-repeat;
		/* background: red; */
	    height: calc(100vh - 60rpx);  /* 根据横版调整为使用vh来控制高度，可根据实际情况微调 */
	    background-size:calc(100vw - 150rpx) calc(100vh - 60rpx) !important;
	    margin: 30rpx 30rpx 30rpx 30rpx;
	   
	   }
	   
	   .pic {
	     width: calc((100vw - 150rpx) / 3 - 4rpx); /* 将rpx改为px */
	     height: calc((100vh - 60px) / 3 - 6rpx); /* 将rpx改为px */
		 background-size:calc(100vw - 140rpx) calc(100vh - 38rpx);
		 position: absolute;
		 transition: all 0.5s ease 0s;
	     
	   }
	 }
/* 华为 Mate60 横屏模式专用样式 */
@supports (height: 1284px) and (width: 2772px) {
  @media screen and (orientation: landscape) {
  /* 主容器布局调整 */
  /* 拼图区域优化 */
  #picbox  {
	    position: relative;
        width: calc(100vw - 170rpx);
		background-repeat: no-repeat;
        height: calc(100vh - 60rpx);  /* 根据横版调整为使用vh来控制高度，可根据实际情况微调 */
        background-size:calc(100vw - 170rpx) calc(100vh - 60rpx);
        margin: 30rpx 30rpx 30rpx 30rpx;
    }
  .pic {
   width: calc((100vw - 170rpx) / 3 - 4px); /* 将rpx改为px */
   height: calc((100vh - 60px) / 3 - 4rpx); /* 将rpx改为px */
   background-size:calc(100vw - 170rpx) calc(100vh - 38rpx);
   position: absolute;
   transition: all 0.5s ease 0s;
  }
  
}}
</style>